package com.vehiclemanagement.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.vehiclemanagement.common.result.Result;
import com.vehiclemanagement.entity.MaintenanceRecord;
import com.vehiclemanagement.service.MaintenanceRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 车辆维修保养记录控制器
 */
@RestController
@RequestMapping("/api/maintenance")
@Slf4j
public class MaintenanceRecordController {

    @Autowired
    private MaintenanceRecordService maintenanceRecordService;

    /**
     * 分页查询维修保养记录
     */
    @GetMapping("/list")
    public Result<IPage<MaintenanceRecord>> list(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String searchTerm,
            @RequestParam(required = false) Long vehicleId,
            @RequestParam(required = false) Integer maintenanceType,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        log.info("分页查询维修保养记录: current={}, size={}, searchTerm={}, vehicleId={}, maintenanceType={}, status={}, startTime={}, endTime={}",
                current, size, searchTerm, vehicleId, maintenanceType, status, startTime, endTime);

        try {
            IPage<MaintenanceRecord> page = maintenanceRecordService.pageMaintenanceRecords(
                    current, size, searchTerm, vehicleId, maintenanceType, status, startTime, endTime);
            return Result.success(page);
        } catch (Exception e) {
            log.error("分页查询维修保养记录失败", e);
            return Result.error("获取维修保养记录列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取维修保养记录详情
     */
    @GetMapping("/{id}")
    public Result<MaintenanceRecord> getById(@PathVariable Long id) {
        log.info("获取维修保养记录详情: id={}", id);

        try {
            MaintenanceRecord record = maintenanceRecordService.getMaintenanceRecordById(id);
            if (record == null) {
                return Result.error("找不到指定的维修保养记录");
            }
            return Result.success(record);
        } catch (Exception e) {
            log.error("获取维修保养记录详情失败", e);
            return Result.error("获取维修保养记录详情失败：" + e.getMessage());
        }
    }

    /**
     * 添加维修保养记录
     */
    @PostMapping
    public Result<Boolean> add(@RequestBody MaintenanceRecord record) {
        log.info("添加维修保养记录: {}", record);

        // 校验必填字段
        if (record.getVehicleId() == null) {
            return Result.validateFailed("车辆ID不能为空");
        }
        if (record.getMaintenanceType() == null) {
            return Result.validateFailed("维修保养类型不能为空");
        }
        if (record.getMaintenanceContent() == null || record.getMaintenanceContent().trim().isEmpty()) {
            return Result.validateFailed("维修保养内容不能为空");
        }

        try {
            boolean success = maintenanceRecordService.addMaintenanceRecord(record);
            return success ? Result.success("添加维修保养记录成功", true) : Result.error("添加维修保养记录失败");
        } catch (Exception e) {
            log.error("添加维修保养记录失败", e);
            return Result.error("添加维修保养记录失败：" + e.getMessage());
        }
    }

    /**
     * 更新维修保养记录
     */
    @PutMapping
    public Result<Boolean> update(@RequestBody MaintenanceRecord record) {
        log.info("更新维修保养记录: {}", record);

        if (record.getId() == null) {
            return Result.validateFailed("维修保养记录ID不能为空");
        }

        try {
            boolean success = maintenanceRecordService.updateMaintenanceRecord(record);
            return success ? Result.success("更新维修保养记录成功", true) : Result.error("更新维修保养记录失败");
        } catch (Exception e) {
            log.error("更新维修保养记录失败", e);
            return Result.error("更新维修保养记录失败：" + e.getMessage());
        }
    }

    /**
     * 删除维修保养记录
     */
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        log.info("删除维修保养记录: id={}", id);

        try {
            boolean success = maintenanceRecordService.deleteMaintenanceRecord(id);
            return success ? Result.success("删除维修保养记录成功", true) : Result.error("删除维修保养记录失败");
        } catch (Exception e) {
            log.error("删除维修保养记录失败", e);
            return Result.error("删除维修保养记录失败：" + e.getMessage());
        }
    }

    /**
     * 开始维修保养
     */
    @PutMapping("/start/{id}")
    public Result<Boolean> startMaintenance(@PathVariable Long id) {
        log.info("开始维修保养: id={}", id);

        try {
            boolean success = maintenanceRecordService.startMaintenance(id);
            return success ? Result.success("开始维修保养成功", true) : Result.error("开始维修保养失败");
        } catch (Exception e) {
            log.error("开始维修保养失败", e);
            return Result.error("开始维修保养失败：" + e.getMessage());
        }
    }

    /**
     * 完成维修保养
     */
    @PutMapping("/complete/{id}")
    public Result<Boolean> completeMaintenance(
            @PathVariable Long id,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime,
            @RequestParam(required = false) BigDecimal maintenanceCost,
            @RequestParam(required = false) BigDecimal partsCost,
            @RequestParam(required = false) BigDecimal laborCost,
            @RequestParam(required = false) Integer isInsuranceClaim,
            @RequestParam(required = false) BigDecimal insuranceClaimAmount,
            @RequestParam(required = false) String remark) {

        log.info("完成维修保养: id={}, endTime={}, maintenanceCost={}, partsCost={}, laborCost={}, isInsuranceClaim={}, insuranceClaimAmount={}, remark={}",
                id, endTime, maintenanceCost, partsCost, laborCost, isInsuranceClaim, insuranceClaimAmount, remark);

        try {
            boolean success = maintenanceRecordService.completeMaintenance(
                    id, endTime, maintenanceCost, partsCost, laborCost, isInsuranceClaim, insuranceClaimAmount, remark);
            return success ? Result.success("完成维修保养成功", true) : Result.error("完成维修保养失败");
        } catch (Exception e) {
            log.error("完成维修保养失败", e);
            return Result.error("完成维修保养失败：" + e.getMessage());
        }
    }

    /**
     * 取消维修保养
     */
    @PutMapping("/cancel/{id}")
    public Result<Boolean> cancelMaintenance(
            @PathVariable Long id,
            @RequestParam(required = false) String remark) {

        log.info("取消维修保养: id={}, remark={}", id, remark);

        try {
            boolean success = maintenanceRecordService.cancelMaintenance(id, remark);
            return success ? Result.success("取消维修保养成功", true) : Result.error("取消维修保养失败");
        } catch (Exception e) {
            log.error("取消维修保养失败", e);
            return Result.error("取消维修保养失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆维修保养总费用
     */
    @GetMapping("/total-cost/vehicle/{vehicleId}")
    public Result<BigDecimal> getTotalCostByVehicleId(@PathVariable Long vehicleId) {
        log.info("获取车辆维修保养总费用: vehicleId={}", vehicleId);

        try {
            BigDecimal totalCost = maintenanceRecordService.sumTotalCostByVehicleId(vehicleId);
            return Result.success(totalCost);
        } catch (Exception e) {
            log.error("获取车辆维修保养总费用失败", e);
            return Result.error("获取车辆维修保养总费用失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆维修保养实际支出总费用
     */
    @GetMapping("/actual-cost/vehicle/{vehicleId}")
    public Result<BigDecimal> getActualCostByVehicleId(@PathVariable Long vehicleId) {
        log.info("获取车辆维修保养实际支出总费用: vehicleId={}", vehicleId);

        try {
            BigDecimal actualCost = maintenanceRecordService.sumActualCostByVehicleId(vehicleId);
            return Result.success(actualCost);
        } catch (Exception e) {
            log.error("获取车辆维修保养实际支出总费用失败", e);
            return Result.error("获取车辆维修保养实际支出总费用失败：" + e.getMessage());
        }
    }

    /**
     * 获取车辆维修保养次数
     */
    @GetMapping("/count/vehicle/{vehicleId}")
    public Result<Integer> getCountByVehicleId(@PathVariable Long vehicleId) {
        log.info("获取车辆维修保养次数: vehicleId={}", vehicleId);

        try {
            Integer count = maintenanceRecordService.countMaintenanceByVehicleId(vehicleId);
            return Result.success(count);
        } catch (Exception e) {
            log.error("获取车辆维修保养次数失败", e);
            return Result.error("获取车辆维修保养次数失败：" + e.getMessage());
        }
    }

    /**
     * 按维修保养类型统计
     */
    @GetMapping("/statistics/type")
    public Result<List<Map<String, Object>>> statisticsByType(
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        log.info("按维修保养类型统计: startTime={}, endTime={}", startTime, endTime);

        try {
            List<Map<String, Object>> statistics = maintenanceRecordService.statisticsByType(startTime, endTime);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("按维修保养类型统计失败", e);
            return Result.error("按维修保养类型统计失败：" + e.getMessage());
        }
    }

    /**
     * 按月份统计维修保养费用
     */
    @GetMapping("/statistics/month")
    public Result<List<Map<String, Object>>> statisticsByMonth(
            @RequestParam(required = false) Integer year) {

        log.info("按月份统计维修保养费用: year={}", year);

        try {
            List<Map<String, Object>> statistics = maintenanceRecordService.statisticsByMonth(year);
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("按月份统计维修保养费用失败", e);
            return Result.error("按月份统计维修保养费用失败：" + e.getMessage());
        }
    }

    /**
     * 查询即将到期需要保养的车辆
     */
    @GetMapping("/vehicles-need-maintenance")
    public Result<List<Map<String, Object>>> findVehiclesNeedingMaintenance(
            @RequestParam(required = false) Double mileageThreshold) {

        log.info("查询即将到期需要保养的车辆: mileageThreshold={}", mileageThreshold);

        try {
            List<Map<String, Object>> vehicles = maintenanceRecordService.findVehiclesNeedingMaintenance(mileageThreshold);
            return Result.success(vehicles);
        } catch (Exception e) {
            log.error("查询即将到期需要保养的车辆失败", e);
            return Result.error("查询即将到期需要保养的车辆失败：" + e.getMessage());
        }
    }

    /**
     * 测试接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("维修保养记录API正常运行");
    }
} 